package cn.platform.util;

import cn.platform.request.AttendanceRecordDTO;
import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.ObjectMapper;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Component;
import org.springframework.web.socket.TextMessage;
import org.springframework.web.socket.WebSocketSession;
import org.springframework.web.socket.handler.TextWebSocketHandler;

import java.util.HashSet;
import java.util.Set;

@Slf4j
@Component
public class AttendanceWebSocketHandler extends TextWebSocketHandler {

    private final Set<WebSocketSession> sessions = new HashSet<>();
    @Override
    public void afterConnectionEstablished(WebSocketSession session) throws Exception {
        sessions.add(session);
        log.info("客户端连接已建立{}",session.getId());
    }

    @Override
    protected void handleTextMessage(WebSocketSession session, TextMessage message) throws Exception {
       log.info("接收到客户端发来的信息{}",message.getPayload());
    }

    public void sendMessageToClient(AttendanceRecordDTO message) throws JsonProcessingException {
        String jsonMessage = new ObjectMapper().writeValueAsString(message);
        for (WebSocketSession session :sessions){
            try {
                session.sendMessage(new TextMessage(jsonMessage));
            }catch (Exception e){
                e.printStackTrace();
            }
        }
    }
}
